let baseUrlDev = "http://zyr.jiuhuakang.com";
let yrz = "http://192.168.30.101:8732";
let baseUrlDev1 = "https://testapi.ygcha.com.cn";
let baseUrl1 = "https://aq.ygcha.com.cn";
let baseUrl2 = "https://qq.tlcha.com.cn";
let baseUrl3 = "https://aq.ruinuomei.com";
let baseUrl4 = "https://aq.jiuhuakang.com";

var httpurl = baseUrl2;
var visitimgurl = "http://small.tlcha.com.cn";
// let visitimgurl = "http://small.muruji.com";
// let visitimgurl = "http://small.ygcha.com.cn";
// let visitimgurl = "http://small.jiuhangyunxuan.cn";


let ii = 0,
    pageNo = 1,
    pageSize = 10,
    token = "",
    totalRecords = 0,
    pageRecords = 10,
    totalPage = 0;
let layer, laypage, element, form, loadmsg, upload, table;
let onkeyupFun = `onkeyup="this.value= this.value.match(/\d+(\.\d{0,2})?/) ? this.value.match(/\d+(\.\d{0,2})?/)[0] : ''"`
/*var htmlinfo='<div class="leftRightInfo">' +
    '<div onclick="tops();" style="background: grey;margin: 10px 0;padding: 2px;cursor:pointer">到顶部↑</div>' +
    '<div onclick="bottoms();" style="background: grey;margin: 10px 0;padding: 2px;cursor:pointer">到底部↓</div>' +
    '</div>';*/
function AllChoose(obj) {
    if ($(obj).is(':checked')) {
        $("#AllChooseList").find("input[type='checkbox']").attr("checked", "checked");
    } else {
        $("#AllChooseList").find("input[type='checkbox']").removeAttr("checked");
    }
};

function parentListFun(obj) {
    let childInfo = $(obj).parent().parent().next().find('input[name="childrenList"]');
    if ($(obj).is(':checked')) {
        // if(childInfo.length>0){
        $(childInfo).attr("checked", "checked");
        // }else{
        //     $(obj).removeAttr("checked");
        // }
    } else {
        $(childInfo).removeAttr("checked");
    }
};

function tops() {
    document.body.scrollTop = document.documentElement.scrollTop = 0;
}

function bottoms() {
    window.scrollTo(0, document.body.scrollHeight);
}

function childrenListFun(obj) {
    if ($(obj).is(':checked')) {
        $(obj).parent().parent().parent().prev().find('input[name="parentList"]').attr("checked", "checked");
    } else {
        let TempParent = $(obj).parent().parent().parent();
        let a = 0;
        for (let i = 0; i < TempParent.length; i++) {
            if ($(TempParent[i]).find('input[name="childrenList"]').is(':checked')) {
                a++;
            }
        }
        if (a == 0) {
            $(obj).parent().parent().parent().prev().find('input[name="parentList"]').removeAttr("checked");
        }
    }
};

$(function () {
    //$("body").prepend(htmlinfo);
    //给全选的复选框添加事件
    $("#all").click(function () {
        // this 全选的复选框
        var userids = this.checked;
        //获取name=box的复选框 遍历输出复选框
        $("input[name=box]").each(function () {
            this.checked = userids;
        });
    });
    token = getCookieValue("token");
    //给name=box的复选框绑定单击事件
    $("input[name=box]").click(function () {
        //获取选中复选框长度
        var length = $("input[name=box]:checked").length;
        //未选中的长度
        var len = $("input[name=box]").length;
        if (length == len) {
            $("#all").get(0).checked = true;
        } else {
            $("#all").get(0).checked = false;
        }
    });
    // -----------禁止用户右键和F12   start   --------------
    // document.onmousedown = function mdClick(event) {
    //     var e = event || window.event || arguments.callee.caller.arguments[0];
    //     if (e.button == 2 || e.button == 3) {
    //         mAlert();
    //     }
    // };
    // document.oncontextmenu = new Function("return false;");
    // document.onkeydown = document.onkeyup = document.onkeypress = function(event) {
    //     var e = event || window.event || arguments.callee.caller.arguments[0];

    //     if (e && e.keyCode == 123) {
    //         mAlert();
    //         e.returnValue = false;
    //         return (false);
    //     }
    // };
    // document.onkeydown = function() {
    //     var e = window.event || arguments[0];
    //     //F12
    //     if (e.keyCode == 123) {
    //         return false;
    //         //Ctrl+Shift+I
    //     } else if ((e.ctrlKey) && (e.shiftKey) && (e.keyCode == 73)) {
    //         return false;
    //         //Shift+F10
    //     } else if ((e.shiftKey) && (e.keyCode == 121)) {
    //         return false;
    //         //Ctrl+U
    //     } else if ((e.ctrlKey) && (e.keyCode == 85)) {
    //         return false;
    //     }
    // };
    // 屏蔽鼠标右键
    // document.oncontextmenu = function() {
    //     return false;
    // }

    // -----------禁止用户右键和F12  end  --------------
    $.ajaxSetup({
        error: function (jqXHR, textStatus, errorThrown) {

        },
        complete: function (res) {
            let data = JSON.parse(res.responseText)
            if (res.status == 200) {
                if(data.rtnCode==401){
                    top.layer.msg('无权限访问，请重新登录哦~')
                }
            }else{
                top.layer.msg('网络异常，请稍后再试')
            }
        },
    });
})

function return_list() {
    let page = GetQueryString("page");
    addCookie("page", page, 1, "/");
    parent.location.reload();
    var index = parent.layer.getFrameIndex(window.name); //获取窗口索引
    parent.layer.close(index);
}
//分页
function pageLayPage(tempName) {
    laypage.render({
        elem: 'page' //注意，这里的 test1 是 ID，不用加 # 号
        ,
        count: totalRecords //数据总数，从服务端得到
        ,
        layout: ['count', 'prev', 'page', 'next', 'refresh', 'skip'],
        curr: pageNo //获取hash值为fenye的当前页
        ,
        hash: 'fenye' //自定义hash值
        ,
        limit: pageSize,
        jump: function (obj, first) {
            //首次不执行
            if (!first) {
                pageNo = obj.curr; // 当前页数;
                pageSize = obj.limit; // 当前页面记录数
                if (tempName == 'SelectUserList') {
                    SelectUserList();
                } else if (tempName == 'SelectCollectList') {
                    SelectCollectList();
                } else if (tempName == 'inituserdata') {
                    inituserdata();
                } else if (tempName == 'initData') {
                    initData();
                } else if (tempName == "myrefresh") {
                    myrefresh();
                } else if (tempName == 'selectAllProductInfoByInfoPc') {
                    selectAllProductInfoByInfoPc();
                }
            }
        }
    });
}

function GetTokenInfo() {
    if (!isNotNull(token)) {
        token = getCookieValue("token")
    }
    return decodeURI(token);
}

function mAlert() {
    // layer.alert("感谢您九航云选APP管理后台,禁止一切想操作控制台的行为！！！");
}

function GetQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return unescape(r[2]);
    return null;
}

//获取父页面的url参数的值
function GetParentQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.parent.location.search.substr(1).match(reg);
    if (r != null) return unescape(r[2]);
    return null;
}
//累加套餐
var rule = '<div class="rules margin_buttom10 display_table" data-id="0">' +
    '<div class="float_left">' +
    '<span class="margin_right10"> 套餐</span><input type="text" value="" class="form-control form-boxed width20 mealname" /><span></span>' +
    '<span class="margin_right10"> 现价</span><input type="number" value="0" onkeyup="updateOldPrice(this);" step="0.01" class="form-control form-boxed width20 mealprice" /><span></span>' +
    '<span class="margin_right10"> 折扣(折)</span><input type="number" value="9" onkeyup="updateOldPrice(this);" step="0.01" class="form-control form-boxed width20 discount" /><span></span>' +
    '<span class="margin_right10"> 市场价</span><input type="number" value="0" step="0.01" class="form-control form-boxed width20 mealoldprice" /><span></span>' +
    '<span class="margin_right10"> 邮费</span><input type="number" value="0" step="0.01" class="form-control form-boxed width20 freight" /><span></span>' +
    '<span class="margin_right10"> 库存</span><input type="number" step="1" value="300" value="0" class="form-control form-boxed width20 mealstock" /><span></span>' +
    '<span class="margin_right10">新人价格</span><input type="number" step="1" value="0" class="form-control form-boxed width20 newspecials" /><span></span>' +

    '</div>' +
    '<div class="float_left padding6 bg_red" onclick="icon_remove(this)"><i class="icon-remove"></i></div>' +
    '</div>';

function icon_remove(r) {
    $(r).parent().remove();
}

//图片上传
function addclick(ac) {
    $(ac).prev().click();
}

function upload_img(obj, tempName) {
    // console.log(tempName + "==upload_img=tempName");
    let files = $(obj).get(0).files;
    let data = new FormData();
    data.append('file', files[0]);
    $.ajax({
        type: "POST",
        url: httpurl + '/uploadImgQiniu?pathName=' + tempName + "&divisor=0&dividend=1",
        data: data,
        cache: false,
        processData: false,
        contentType: false,
        success: function (data) {
            if (data.rtnCode == 200) {
                if (tempName == 'productImg') { //上传商品图片
                    $(obj).parent().parent().next().find("img").attr("src", visitimgurl + "/" + data.msg);
                    $(obj).parent().parent().next().find("img").attr("name", data.msg);
                    $(obj).parent().parent().next().show();
                } else if (tempName == 'headimg') { //上传用户头像成功
                    $(obj).parent().find("#headimg").attr("src", visitimgurl + "/" + data.msg);
                    $(obj).parent().find("#headimg").attr("name", data.msg);
                }
            } else {
                top.layer.alert(data.msg, function (index) {
                    layer.close(index);
                });
            }
        },
        error: function () {
            //console.log("==error==");
        }
    });

}

//二.js把时间戳转为为普通日期格式
//1.Date toLocaleString方法
function getLocalTime(nS) {
    return new Date(parseInt(nS) * 1000).toLocaleString().replace(/:\d{1,2}$/, ' ');
}

//查询指定月份有多少天
function SelectDays(year, month) {
    return new Date(year, month, 0).getDate();
}

//获取本月的天数
function SelectThisDays() {
    let d = new Date();
    //d.getMonth()+1代表下个月，月份索引从0开始，即当前月为6月时，getMonth()返回值为5，创建日期时同理
    //此处构造的日期为下个月的第0天，天数索引从1开始，第0天即代表上个月的最后一天
    let curMonthDays = new Date(d.getFullYear(), (d.getMonth() + 1), 0).getDate();
    let arr = [];
    for (let i = 1; i <= curMonthDays; i++) {
        arr.push(i);
    }
    // alert("本月共有 "+ curMonthDays +" 天");
    return arr;
}

function isNotNull(str) {
    if (str != null && str != undefined && str != '' && str != 'null') return true;
    return false;
}

function closeAllLayer() {
    top.layer.closeAll();
    layer.closeAll();
}
//获取当前年份的前5后2年年份
function SelectYearInfo() {
    let myDate = new Date();
    let ThisYear = myDate.getFullYear(); //获取完整的年份(4位)
    let arr = [];
    for (let i = (ThisYear - 5); i <= (ThisYear + 2); i++) {
        // arr.push(i+"年");
        arr.push(i);
    }
    return arr;
}

//处理大数据
function unitConvert(num) {
    var moneyUnits = ["", "万", "亿", "万亿"]
    var dividend = 10000;
    var curentNum = num; //转换数字
    var curentUnit = moneyUnits[0]; //转换单位
    for (var i = 0; i < 4; i++) {
        curentUnit = moneyUnits[i];
        if (strNumSize(curentNum) < 5) {
            break;
        }
        curentNum = curentNum / dividend;
    }
    var m = { num: 0, unit: "" };
    m.num = curentNum.toFixed(2);
    m.unit = curentUnit;
    return m;
}

function timestampToTime(str) {
    var oDate = new Date(str),
        oYear = oDate.getFullYear(),
        oMonth = oDate.getMonth() + 1,
        oDay = oDate.getDate(),
        oHour = oDate.getHours(),
        oMin = oDate.getMinutes(),
        oSen = oDate.getSeconds(),
        oTime = oYear + '-' + getzf(oMonth) + '-' + getzf(oDay) + ' ' + getzf(oHour) + ':' + getzf(oMin) + ':' + getzf(oSen); //最后拼接时间
    return oTime;
};
//补0操作
function getzf(num) {
    if (parseInt(num) < 10) {
        num = '0' + num;
    }
    return num;
}

function strNumSize(tempNum) {
    var stringNum = tempNum.toString();
    var index = stringNum.indexOf(".");
    var newNum = stringNum;
    if (index != -1) {
        newNum = stringNum.substring(0, index);
    }
    return newNum.length;
}


//记住密码
function addCookie(name, value, days, path) {
    /**添加设置cookie**/
    var name = escape(name);
    var value = escape(value);
    var expires = new Date();
    expires.setTime(expires.getTime() + days * 3600000 * 24);
    //path=/，表示cookie能在整个网站下使用，path=/temp，表示cookie只能在temp目录下使用
    path = path == "" ? "" : ";path=" + path;
    //GMT(Greenwich Mean Time)是格林尼治平时，现在的标准时间，协调世界时是UTC
    //参数days只能是数字型
    var _expires = (typeof days) == "string" ? "" : ";expires=" + expires.toUTCString();
    document.cookie = name + "=" + value + _expires + path;
}

function getCookieValue(name) {
    /**获取cookie的值，根据cookie的键获取值**/
    //用处理字符串的方式查找到key对应value
    var name = escape(name);
    //读cookie属性，这将返回文档的所有cookie
    var allcookies = document.cookie;
    //查找名为name的cookie的开始位置
    name += "=";
    var pos = allcookies.indexOf(name);
    //如果找到了具有该名字的cookie，那么提取并使用它的值
    if (pos != -1) { //如果pos值为-1则说明搜索"version="失败
        var start = pos + name.length; //cookie值开始的位置
        var end = allcookies.indexOf(";", start); //从cookie值开始的位置起搜索第一个";"的位置,即cookie值结尾的位置
        if (end == -1) end = allcookies.length; //如果end值为-1说明cookie列表里只有一个cookie
        var value = allcookies.substring(start, end); //提取cookie的值
        return (value); //对它解码
    } else { //搜索失败，返回空字符串
        return "";
    }
}

function deleteCookie(name, path) {
    /**根据cookie的键，删除cookie，其实就是设置其失效**/
    var name = escape(name);
    var expires = new Date(0);
    path = path == "" ? "" : ";path=" + path;
    document.cookie = name + "=" + ";expires=" + expires.toUTCString() + path;
}


var Base64 = {
    _keyStr: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
    encode: function (e) {
        var t = "";
        var n, r, i, s, o, u, a;
        var f = 0;
        e = Base64._utf8_encode(e);
        while (f < e.length) {
            n = e.charCodeAt(f++);
            r = e.charCodeAt(f++);
            i = e.charCodeAt(f++);
            s = n >> 2;
            o = (n & 3) << 4 | r >> 4;
            u = (r & 15) << 2 | i >> 6;
            a = i & 63;
            if (isNaN(r)) {
                u = a = 64
            } else if (isNaN(i)) {
                a = 64
            }
            t = t + this._keyStr.charAt(s) + this._keyStr.charAt(o) + this._keyStr.charAt(u) + this._keyStr.charAt(a)
        }
        return t
    },
    decode: function (e) {
        var t = "";
        var n, r, i;
        var s, o, u, a;
        var f = 0;
        e = e.replace(/[^A-Za-z0-9+/=]/g, "");
        while (f < e.length) {
            s = this._keyStr.indexOf(e.charAt(f++));
            o = this._keyStr.indexOf(e.charAt(f++));
            u = this._keyStr.indexOf(e.charAt(f++));
            a = this._keyStr.indexOf(e.charAt(f++));
            n = s << 2 | o >> 4;
            r = (o & 15) << 4 | u >> 2;
            i = (u & 3) << 6 | a;
            t = t + String.fromCharCode(n);
            if (u != 64) {
                t = t + String.fromCharCode(r)
            }
            if (a != 64) {
                t = t + String.fromCharCode(i)
            }
        }
        t = Base64._utf8_decode(t);
        return t
    },
    _utf8_encode: function (e) {
        e = e.replace(/rn/g, "n");
        var t = "";
        for (var n = 0; n < e.length; n++) {
            var r = e.charCodeAt(n);
            if (r < 128) {
                t += String.fromCharCode(r)
            } else if (r > 127 && r < 2048) {
                t += String.fromCharCode(r >> 6 | 192);
                t += String.fromCharCode(r & 63 | 128)
            } else {
                t += String.fromCharCode(r >> 12 | 224);
                t += String.fromCharCode(r >> 6 & 63 | 128);
                t += String.fromCharCode(r & 63 | 128)
            }
        }
        return t
    },
    _utf8_decode: function (e) {
        var t = "";
        var n = 0;
        var r = c1 = c2 = 0;
        while (n < e.length) {
            r = e.charCodeAt(n);
            if (r < 128) {
                t += String.fromCharCode(r);
                n++
            } else if (r > 191 && r < 224) {
                c2 = e.charCodeAt(n + 1);
                t += String.fromCharCode((r & 31) << 6 | c2 & 63);
                n += 2
            } else {
                c2 = e.charCodeAt(n + 1);
                c3 = e.charCodeAt(n + 2);
                t += String.fromCharCode((r & 15) << 12 | (c2 & 63) << 6 | c3 & 63);
                n += 3
            }
        }
        return t
    }
};
function pageBack() {
    window.history.go(-pageNo)
}
//数组对象深拷贝
function deepCopy(obj) {
  var newobj = obj.constructor === Array ? [] : {};
  if (typeof obj !== "object") {
    return;
  }
  for (var i in obj) {
    newobj[i] = typeof obj[i] === "object" ? deepCopy(obj[i]) : obj[i];
  }
  return newobj;
}

